<template>
    <div class="write-holleave">
        <!-- 操作結果提示 -->
        <msg v-if="doneShow" class="done-msg" :icon="doneIcon">
            <template slot="buttons">
                <router-link class="success-btn" v-if="doneIcon === 'success'" :to="{ name: 'InitiateApplication'}">
                    返回首页
                </router-link>
                <a class="success-btn" v-else @click="closeDoneInfo">返回更改例假申请</a>
            </template>
            <template slot="description">
                <p class="title">{{doneTitle}}</p>
                <p>{{doneMsg}}</p>
            </template>
        </msg>

        <div class="scroll-box" v-show="!doneShow">
            <!-- 更改例假信息填寫 -->
            <my-hol-leave-info ref="holLeaveInfo"></my-hol-leave-info>
            <!-- 附件 -->
            <my-annex ref="annex"></my-annex>
            <!-- 抄送人 -->
            <my-make-copy ref="makeCopy" :makeCopyParams="makeCopyParams"></my-make-copy>
        </div>

        <!-- 底部組件 -->
        <my-bottom-submit v-if="!doneShow" @click.native="applySubmit"></my-bottom-submit>
        <!-- 加载中 -->
        <loading class="loading-mask" :show="loadingShow" text="加载中..."></loading>
        <!-- 提示彈窗 -->
        <div v-transfer-dom>
            <confirm v-model="turndownShow"
                class="turndown-confirm" title="提示" confirm-text="确认" :show-cancel-button="false">
                <p>{{turndownText}}</p>
            </confirm>
        </div>
    </div>
</template>

<script>
import HolLeaveInfo from '@/components/ApplyWrite/HolLeaveInfo.vue';
import MakeCopy from '@/components/ApplyWrite/MakeCopy.vue';
import BottomSubmit from '@/components/Bottom/BottomSubmit.vue';
import { Msg, Loading, Confirm, TransferDom } from 'vux';
import qs from 'qs';
export default {
    name: 'WriteHolLeave',
    data() {
        return {
            defaultMakeCopyStaffNo01:'1607245',
            defaultMakeCopyStaffNo02:'1911926',
            defaultMakeCopyStaffNo03:'2003036',

            // 操作结果控制
            doneIcon: '',
            doneTitle: '',
            doneMsg: '',
            doneShow: false,

            loadingShow: false,
            turndownShow: false,
            turndownText: '',
            makeCopyParams: [],
            // 必填字段
            required: ['StartDate', 'EndDate', 'Reason'] 
        }
    },
    directives: {
      TransferDom
    },
    components: {
      Msg,
      Loading,
      Confirm,
      'my-hol-leave-info': HolLeaveInfo,
      'my-make-copy': MakeCopy,
      'my-bottom-submit': BottomSubmit,
      'my-annex': ()=>import('@/components/ApplyWrite/Annex.vue'),
    },

    async mounted() {
        await this.pageInit();
        if(this.$refs.makeCopy.resultList.length === 0) {
            this.$refs.makeCopy.resultList = this.makeCopyParams;
        }
    },
    watch: {
        $route (to, from) {
            setTimeout(() => {
                this.loadingShow = false;
                this.changeDoneInfo(false);
            }, 500);
            this.pageInit(to, from);
        }
    },
    methods: {
        // 頁面初始化
        pageInit: async function (to, from) {
            let isHomeToThisPage;
            if(to && from) {
                isHomeToThisPage = from.name === 'InitiateApplication' && this.$route.name === 'WriteHolLeave';
            }
            let isReApplyToThisPage = this.$route.query.applyInfo;
            if (isHomeToThisPage) {
                this.$refs.holLeaveInfo.startDate = '';
                this.$refs.holLeaveInfo.endDate = '';
                this.$refs.holLeaveInfo.reasonText = '';
                this.$refs.holLeaveInfo.changeApplyType = ''

                this.required.pop();
                this.makeCopyParams = await this.getDefaultMakeCopy();
            } else if(from && from.name === 'SelectPerson' && this.$route.name === 'WriteHolLeave'){
            } else if(isReApplyToThisPage && this.$route.name === 'WriteHolLeave') {
                // 修改申请
                let params = JSON.parse(isReApplyToThisPage);
                let startDate = params.Content.StartDate;
                let endDate = params.Content.EndDate;
                this.makeCopyParams = await this.getDefaultMakeCopy();
                let copiers = params.Copiers.slice(3, params.Copiers.length); // 正式
                // let copiers = params.Copiers; // 测试
                if (copiers.length !== 0) {
                    this.getReApplyMakeCopy(copiers);
                }
                setTimeout(() => {
                    this.$refs.holLeaveInfo.startDate = startDate.slice(0, startDate.lastIndexOf(':')).replace(/T/g, ' ');
                    this.$refs.holLeaveInfo.endDate = endDate.slice(0, endDate.lastIndexOf(':')).replace(/T/g, ' ');
                }, 0);
                this.$refs.holLeaveInfo.reasonText = params.Content.Reason;

                if (this.$route.query.titleName === '修改申请') {
                    // this.$refs.holLeaveInfo.reApplyReasonShow = true;
                    this.$refs.holLeaveInfo.editApplyReason = '';
                    this.required.push('EditApplyReason');
                    this.$refs.holLeaveInfo.changeApplyType = '修改申请原因';
                } else if (params.IsReApply === true) {
                    this.$refs.holLeaveInfo.reApplyReason = '';
                    this.required.push('ReApplyReason');
                    this.$refs.holLeaveInfo.changeApplyType = '重新申请原因';
                }
            } else {
                this.makeCopyParams = await this.getDefaultMakeCopy();
            }
        },
        // 提交事件
        applySubmit: function () {
            if (this.loadingShow) {
                return false;
            }
            let ContentData = {
                Reason: this.$refs.holLeaveInfo.reasonText,
                StartDate: this.$refs.holLeaveInfo.startDate,
                EndDate: this.$refs.holLeaveInfo.endDate,
                files: this.$refs.annex.fileList,
            };
            if (this.$refs.holLeaveInfo.changeApplyType === '重新申请原因') {
                ContentData.ReApplyReason = this.$refs.holLeaveInfo.reApplyReason;
            }
            if (this.$refs.holLeaveInfo.changeApplyType === '修改申请原因') {
                ContentData.EditApplyReason = this.$refs.holLeaveInfo.editApplyReason;
            }
            // 需要post的數據
            let postData = {
                data: {
                    Type: 5,    // 提交类型
                    CreatedStaffNo: this.getUserInfo().StaffNo,
                    Copiers: this.parseCopiers(),
                    Content: JSON.stringify(ContentData)
                }
            };
            // console.log(ContentData);
            // console.log(postData);
            for(let prop in this.required) {
                let propName = this.required[prop];
                if(ContentData[propName].trim() === '') {
                    this.turndownText = '请输入必填项';
                    this.turndownShow = true;
                    return false;
                }
            }

            if (this.$route.query && this.$route.query.titleName === '修改申请') {
                postData.data.KeyId = JSON.parse(this.$route.query.applyInfo).KeyId;
                console.log('修改',postData);
                this.editRequest(postData);
            } else {
            if (this.$route.query.applyInfo !== undefined) {
                let query = JSON.parse(this.$route.query.applyInfo);
                if (query.IsReApply !== undefined) {
                    postData.data.IsReApply = query.IsReApply;
                }
            }
                this.createRequest(postData);
            }
        },
        // 编辑申请
        editRequest: function (params) {
            this.loadingShow = true;
            this.axios.post('/Process/EditAskForLeaveInfo', qs.stringify(params))
            .then((res) => {
                console.log('编辑接口',res);
            if (res.data.IsSuccess === true) {
                this.loadingShow = false;
                this.changeDoneInfo(true, 'success', '提交修改成功', '你的申请已成功提交修改，等待上级领导审批中');
            } else {
                this.loadingShow = false;
                this.changeDoneInfo(true, 'warn', '提交修改失败', `你的申請未能成功提交修改，具体错误：${res.data.ExMessage}`);
            }
            })
            .catch((err) => {
                this.loadingShow = false;
                this.changeDoneInfo(true, 'warn', '提交修改失败', `你的申請未能成功提交修改，具体错误：${err}`);
            });
        },
        // 创建申请
        createRequest: function (params) {
            this.loadingShow = true;
            this.axios.post('/Process/Create', qs.stringify(params))
            .then((res) => {
            if (res.data.IsSuccess === true) {
                this.loadingShow = false;
                this.changeDoneInfo(true, 'success', '提交申请成功', '你的申请已成功提交，等待上级领导审批中');
            } else {
                this.loadingShow = false;
                this.changeDoneInfo(true, 'warn', '提交申请失败', `你的申请未能成功提交，具体错误：${res.data.ExMessage}`);
            }
            })
            .catch((err) => {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'warn', '提交申请失败', `你的申请未能成功提交，具体错误：${err}`);
            });
        },
        changeDoneInfo: function (status, iconType, title, msg) {
            this.doneIcon = iconType;
            this.doneTitle = title;
            this.doneMsg = msg;
            this.doneShow = status;
        },
        closeDoneInfo: function () {
            this.changeDoneInfo(false, '', '', '');
        },
        // 抄送人格式轉換 （只POST StaffNo）
        parseCopiers: function () {
            let copiers = this.$refs.makeCopy.resultList;
            let newCopiers = [];
            copiers.forEach((item) => {
                newCopiers.push({StaffNo: item.userid});
            });
            return newCopiers;
        },
        // 获取默认抄送人
        getDefaultMakeCopy:async function () {
            let postData = {
                data: {
                    StaffNoArr: [
                        {StaffNo:this.defaultMakeCopyStaffNo01},
                        {StaffNo:this.defaultMakeCopyStaffNo02},
                        {StaffNo:this.defaultMakeCopyStaffNo03}
                    ]
                }
            };
            this.loadingShow = true;
            try {
                let res = await this.axios.post('/Wechat/QueryUsersFromStaffNo', qs.stringify(postData))
                this.loadingShow = false;
                if(res.data.IsSuccess === true) {
                    for(var item of res.data.data.Users) {
                        item["checked"] = true;
                        item["removeSwitch"] = false;
                    }
                    let makeCopyArr = res.data.data.Users;
                    return makeCopyArr;
                } else {
                    this.turndownShow = true;
                    this.turndownText = '获取默认抄送人失败';
                    return [];
                }
            } catch(err){
                this.loadingShow = false;
                this.turndownShow = true;
                this.turndownText = '获取默认抄送人失败';
                console.log(err)
                return [];
            }
        },
        getReApplyMakeCopy: function (staffNoArr) {
            if (staffNoArr.length === 0) {
                return false;
            }
            let postData = {
                data: {
                    StaffNoArr: staffNoArr
                }
            };
            this.loadingShow = true;
            return this.axios.post('/Wechat/QueryUsersFromStaffNo', qs.stringify(postData))
                .then((res) => {
                    this.loadingShow = false;
                    if (res.data.IsSuccess === true) {
                        this.makeCopyParams = this.makeCopyParams.concat(res.data.data.Users);
                        this.$refs.makeCopy.resultList = this.makeCopyParams;
                    } else {
                        this.turndownShow = true;
                        this.turndownText = '获取抄送人失败';
                    }
                })
                .catch(() => {
                    this.loadingShow = false;
                    this.turndownShow = true;
                    this.turndownText = '获取抄送人失败';
                });
        }
    },
}
</script>

<style lang="scss" scoped>
    @import '../../assets/style/variable';
    .write-holleave{
        -webkit-overflow-scrolling: touch;
    }
</style>